package mylog

import (
	"fmt"
	"github.com/fatih/color"
	"github.com/sirupsen/logrus"
	"os"
	"path/filepath"
	"strings"
)

type CustomFormatter struct {
	logrus.TextFormatter
	UseColor bool
}

func getRelativePath(entry *logrus.Entry) (string, error) {
	// 获取当前工作目录
	currentDir, err := os.Getwd()
	if err != nil {
		return "", err
	}

	// 获取文件路径
	filePath := entry.Caller.File

	// 计算相对路径
	relativePath, err := filepath.Rel(currentDir, filePath)
	if err != nil {
		return "", err
	}

	return relativePath, nil
}

func (f *CustomFormatter) Format(entry *logrus.Entry) ([]byte, error) {
	timestamp := entry.Time.Format(f.TimestampFormat)
	level := strings.ToUpper(entry.Level.String())
	msg := entry.Message
	originFile := entry.Caller.File
	line := entry.Caller.Line

	// 获取当前的文件和行号信息
	//_, file, line, _ := runtime.Caller(6)
	file := filepath.Base(originFile)

	// 获取当前函数名
	//pc, _, _, _ := runtime.Caller(3)
	//funcName := runtime.FuncForPC(pc).Name()
	//funcName = filepath.Ext(funcName) + "(" + funcName + ")"
	if f.UseColor {
		// 构建格式化后的日志行
		levelColorized := f.getColorizedLevel(level)
		timestampColorized := f.getColorizedTimestamp(timestamp)
		//fileColorized := f.getColorizedFile(file)
		msgColorized := f.getColorizedMsg(msg)
		//link := fmt.Sprintf("<a href='file://%s:%d'>%s:%d</a>", originFile, line, fileColorized, line)

		path, _ := getRelativePath(entry)
		link := fmt.Sprintf(" %s:%d ", path, line)

		lineStr := fmt.Sprintf("%s-[%s]-%s %s %s\n", timestampColorized, levelColorized, link, "\033[37m"+"==>"+"\033[0m", msgColorized)
		return []byte(lineStr), nil
	} else {
		lineStr := fmt.Sprintf("%s-[%s]-%s:%d ==> %s\n", timestamp, level, file, line, msg)
		return []byte(lineStr), nil
	}

}

func (f *CustomFormatter) getColorizedLevel(level string) string {
	switch level {
	case "DEBUG":
		return "\033[36m" + level + "\033[0m"
	case "INFO":
		//return color.New(color.FgGreen).SprintFunc()(level)
		return "\033[32m" + level + "\033[0m"
	case "WARN", "WARNING":
		//return color.New(color.FgYellow).SprintFunc()(level)
		return "\033[33m" + level + "\033[0m"
	case "ERROR":
		return "\033[31m" + level + "\033[0m"
	case "FATAL", "PANIC":
		return "\033[35m" + level + "\033[0m"
	default:
		return level
	}
}

func (f *CustomFormatter) getColorizedTimestamp(timestamp string) string {
	return color.New(color.FgHiBlack).SprintFunc()(timestamp)
}

func (f *CustomFormatter) getColorizedFile(file string) string {
	return color.New(color.FgBlue).SprintFunc()(file)
}

func (f *CustomFormatter) getColorizedMsg(msg string) string {
	return color.New(color.FgWhite).SprintFunc()(msg)
}
